<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
 * 后台进程
*/
class Process extends BaseController {

	public function __construct() {
        parent::__construct();
        // 加载类库
        $this->load->model('schoolModel');
        $this->load->model('classesModel');
        $this->load->model('contentModel');
        $this->load->model('wxUserModel');
        $this->load->library('wxtemplate');
    }

    // 发送微信模板消息
    public function sendTemplate() {
        $process = $this->wxUserModel->get_template_process();
        // var_export($processList);exit;
        if($process) {
            $this->db->update(WxUserModel::$wxTemplateProcessTable, array(
                'is_delete' => 1
            ), array(
                'id' => $process['id']
            ));

            $this->load->library('wxtemplate');
            if($process['type'] == 'class') {
                $this->wxtemplate->send_template_msg($process['class_ids'], $process['template_id'], json_decode($process['data'], true), $process['url'], $process['include_expired']);
            } elseif($process['type'] == 'school') {
                $this->wxtemplate->send_template_msg_for_school($process['school_id'], $process['template_id'], json_decode($process['data'], true), $process['url']);
            } elseif($process['type'] == 'student') {
                $dataArr = json_decode($process['data'], true);
                foreach($dataArr as $data) {
                    $studentId = $data['student_id'];
                    $templateData = $data['data'];
                    // 添加消息接收用户信息，用于自动登录
                    if(!strstr($process['url'], 'bind_user_type=')) {
                       // 只需一个
                       $process['url'] .= '?bind_user_type=' . BIND_TYPE_STUDENT . '&user_id=' . $data['student_id'];
                    }
                    
                    // 成绩通知url，添加student_id请求参数
                    if($process['template_id'] == WX_TEMPLATE_RESULT_NOTIFY) {
                        $url = $process['url'] . '&student_id=' . $studentId;
                        $this->wxtemplate->send_template_msg_for_user($studentId, BIND_TYPE_STUDENT, $process['template_id'], $templateData, $url, $process['include_expired']);
                    } else {
                        $this->wxtemplate->send_template_msg_for_user($studentId, BIND_TYPE_STUDENT, $process['template_id'], $templateData, $process['url'], $process['include_expired']);
                    }
                }
            } elseif($process['type'] == 'teacher') {
                $dataArr = json_decode($process['data'], true);
                foreach($dataArr as $data) {
                    $teacherId = $data['student_id'];
                    // 添加消息接收用户信息，用于自动登录
                    if(!strstr($process['url'], 'bind_user_type=')) {
                        // 只需一个
                        $process['url'] .= '?bind_user_type=' . BIND_TYPE_TEACHER . '&user_id=' . $data['student_id'];
                    }
                    $templateData = $data['data'];
                    $this->wxtemplate->send_template_msg_for_user($teacherId, BIND_TYPE_TEACHER, $process['template_id'], $templateData, $process['url'], $process['include_expired']);
                }
            }
            
            exit(json('发送模板消息成功', true));
        } else {
            exit(json('找不到需要发送的任务', false));
        }
        // if() {
        //     $url = 'http://baidu.com';
        //     $data = array(
        //         'keyword1' => array(
        //             'value' => '1'
        //         ),
        //         'keyword2' => array(
        //             'value' => 'cc'
        //         )
        //     );
        //     for($i=1;$i<=300;$i++) {
        //         $data['keyword1'] = array(
        //             'value' => $i
        //         );
        //         // $this->wxtemplate->send_template_msg_for_user(964, BIND_TYPE_STUDENT, WX_TEMPLATE_HOMEWORK, $data, $url);
        //         $this->wxtemplate->send_template_msg_for_user(2711, BIND_TYPE_STUDENT, WX_TEMPLATE_HOMEWORK, $data, $url);
        //     }
        // }
    }

    // 定时同步
    public function timingHzySync() {
        // 定时同步黄流中学，一天执行三次，4点-5点，11-12点，19-20点间就执行同步
        // 定时同步河西中学，一天执行一次，4点-5点间就执行同步
        $isExecute = false;
        $isExecuteHuangliu = false;
        $isExecuteHexi = false;
        $hour = (int) date('H');
        if($hour == 4 || $hour == 12 || $hour == 19) {
            // 黄流中学
            $isExecute = true;
            $isExecuteHuangliu = true;
        }
        if($hour == 4) {
            // 河西中学
            $isExecute = true;
            $isExecuteHexi = true;
        }
        if($isExecute) {
            if($isExecuteHuangliu) {
                // 获取黄流中学
                $school = $this->schoolModel->get_school_info_by_x_id(3597);
                if($school) {
                    $url = admin_url('hzy/update_hzy_school/') . $school['id'];
                    $result = $this->curl_get($url);
                    if(strstr($result, '同步数据成功')){
                        // 插入日志
                        $this->save_log($school['id']);
                    }
                }

            }
            if($isExecuteHexi) {
                // 获取河西中学
                $school = $this->schoolModel->get_school_info_by_x_id(25166696);
                if($school) {
                    $url = admin_url('hzy/update_hzy_school/') . $school['id'];
                    $result = $this->curl_get($url);
                    if(strstr($result, '同步数据成功')){
                        // 插入日志
                        $this->save_log($school['id']);
                    }
                }
            }
            // echo'<pre>';var_export($result);exit;
        }

        $msg = $isExecute ? '同步成功' : '无须同步';
        exit(json('任务执行成功,' . $msg, true));
    }
    // 定时同步，所有学校（暂不使用）
    public function timingHzySyncAllSchools() {
        // 4点-5点间就执行同步
        $isExecute = false;
        $hour = (int) date('H');
        if($hour == 4) {
            $isExecute = true;
        }
        if($isExecute) {
            $this->load->library('logger');
            // 获取所有学校
            $schoolParams['isDelete'] = 0;
            $schoolParams['schoolFrom'] = X_DATA_HAOZHUANYE;
            $schoolList = $this->schoolModel->get_school_list($schoolParams);
            // echo'<pre>';var_export($schoolList);exit;
            foreach($schoolList as $school) {
                $url = admin_url('hzy/update_hzy_school/') . $school['id'];
                $result = file_get_contents($url);
                $result = json_decode($result, true);
                if($result['success']) {
                    // 插入日志
                    $params['schoolId'] = $school['id'];
                    $params['isDelete'] = 0;
                    $campusList = $this->schoolModel->get_campus_list($params);
                    $campusInfo = $campusList[0];
                    // 插入日志

                    $actionType = $this->logger->get_action_type('sync');
                    if($actionType == false) {
                        throw new Exception('日志错误');
                    }
                    $dataArr = array(
                        'school_id' => $school['id'],
                        'campus_id' => $campusInfo['id'],
                        'user_type' => USER_TYPE_SUPER_ADMIN,
                        'user_id' => 0,
                        'realname' => '',
                        'action_type' => $actionType,
                        'content' => '定时同步数据'
                    );
                    $this->logger->save_log_action($dataArr);
                }
                // echo '<pre>';var_export($result);exit;
                
            }

        }
        $msg = $isExecute ? '同步成功' : '无须同步';
        exit(json('任务执行成功,' . $msg, true));
    }

    public function curl_get($url){
        $header = array(
            'Accept: application/json',
         );
         $curl = curl_init();
         //设置抓取的url
         curl_setopt($curl, CURLOPT_URL, $url);
         //设置头文件的信息作为数据流输出
         curl_setopt($curl, CURLOPT_HEADER, 0);
        //  // 超时设置,以秒为单位
        //  curl_setopt($curl, CURLOPT_TIMEOUT, 1);
      
         // 超时设置，以毫秒为单位
         // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);
      
         // 设置请求头
         curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
         //设置获取的信息以文件流的形式返回，而不是直接输出。
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
         curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
         //执行命令
         $data = curl_exec($curl);
      
         // 显示错误信息
         if (curl_error($curl)) {
             print "Error: " . curl_error($curl);
         } else {
             curl_close($curl);
         }
         return $data;
    }

    // 插入日志
    private function save_log($schoolId) {
        $this->load->library('logger');
        $params['schoolId'] = $schoolId;
        $params['isDelete'] = 0;
        $campusList = $this->schoolModel->get_campus_list($params);
        $campusInfo = $campusList[0];
        // 插入日志

        $actionType = $this->logger->get_action_type('sync');
        if($actionType == false) {
            throw new Exception('日志错误');
        }
        $dataArr = array(
            'school_id' => $schoolId,
            'campus_id' => $campusInfo['id'],
            'user_type' => USER_TYPE_SUPER_ADMIN,
            'user_id' => 0,
            'realname' => '',
            'action_type' => $actionType,
            'content' => '定时同步数据'
        );
        $this->logger->save_log_action($dataArr);
    }
}